$(document).ready(function() {
	//Selects
	var CONTENT = $('#create-test-modal');
	var BUTTONS = CONTENT.find('button');
	var ALERT_ERROR = $('<div id="create-test-error" class="alert alert-error"><button type="button" class="close" data-dismiss="alert">&times;</button><strong>Error!</strong> Unable to create test.</div>');
	
	var CREATE_PROGRESS_CHECK = $('#create-progress-check');
	var PROGRESS_CHECK_FORM = $('#create-progress-check-form');
	
	var CREATE_EXERCISE = $('#create-exercise');
	var EXERCISE_FORM = $('#create-exercise-form')
	

	//Enable buttons
	disableButtons(false);

	/**
	 *	Listeners
	 */
	CREATE_EXERCISE.on('click', function() {
		disableButtons(true);
		transformToExercise();
	});

	CREATE_PROGRESS_CHECK.on('click', function() {
		disableButtons(true);
		transformToProgressCheck();
	});

	/**
	 *	Sends transform to exercise request with ajax.
	 */
	function transformToExercise() {
		$.ajax({
			type: 'POST',
			url: EXERCISE_FORM.attr('action'),
			dataType: 'HTML',
			success: ajaxSuccess,
			error: ajaxError
		});
	}

	/**
	 *	Sends transform to progress check request with ajax.
	 */
	function transformToProgressCheck() {
		$.ajax({
			type: 'POST',
			url: PROGRESS_CHECK_FORM.attr('action'),
			dataType: 'HTML',
			success: ajaxSuccess,
			error: ajaxError
		});
	}

	/**
	 * Called upon ajax success
	 */
	function ajaxSuccess(response) {
		location.reload();
	}

	/**
	 * Called upon ajax error
	 */
	function ajaxError(response) {
		disableButtons(false);
		showError();
	}

	/**
	 *	Shows the error box.
	 */
	 function showError() {
	 	if(! $('#create-test-error').length) {
	 		CONTENT.append(ALERT_ERROR);
	 	}
	 }

	/**
	 * Enable/disable buttons.
	 */
	function disableButtons(disable) {
		BUTTONS.prop('disabled', disable);
	}

});